package com.guslegend.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guslegend.enums.BizCodeEnum;
import com.guslegend.exception.BizException;
import com.guslegend.mapper.CouponRecordMapper;
import com.guslegend.model.CouponDO;
import com.guslegend.model.CouponRecordDO;
import com.guslegend.util.CommonUtil;
import com.guslegend.vo.CouponVO;
import org.springframework.beans.BeanUtils;

/**
 * @author: guslegend
 * @description:
 * @create: 2025-06-04 21:51
 **/
public class CouponUtil {

    /**
     * 检验优惠券是否可以领取
     * @param couponDO 优惠券
     * @param userId   用户id
     * @return
     */
    public static void checkCoupon(CouponDO couponDO, Long userId, CouponRecordMapper couponRecordMapper) {
        //是否存在
        if (couponDO == null) {
            throw new BizException(BizCodeEnum.COUPON_NO_EXITS);
        }
        //库存是否充足
        if (couponDO.getStock() <= 0) {
            throw new BizException(BizCodeEnum.COUPON_NO_STOCK);
        }
        //时间是否满足
        long now = CommonUtil.getCurrentTimeMillis();
        long start = couponDO.getStartTime().getTime();
        long end = couponDO.getEndTime().getTime();
        if (now < start || now > end) {
            throw new BizException(BizCodeEnum.COUPON_OUT_OF_TIME);
        }
        //个人领取是否达到上限
        int count = couponRecordMapper.selectCount(new QueryWrapper<CouponRecordDO>().eq("user_id", userId).eq("coupon_id", couponDO.getId()));
        if (count >= couponDO.getUserLimit()) {
            throw new BizException(BizCodeEnum.COUPON_OUT_OF_LIMIT);
        }
    }

    /**
     * DO转VO
     * @param couponDo
     * @return
     */
    public static CouponVO ObjParse(CouponDO couponDo) {
        CouponVO couponVO = new CouponVO();
        BeanUtils.copyProperties(couponDo, couponVO);
        return couponVO;
    }
}

